package com.txl.mycamera;

import android.graphics.SurfaceTexture;
import android.hardware.Camera;
import android.opengl.GLES20;
import android.opengl.GLSurfaceView;
import android.os.Bundle;
import android.util.Log;
import android.view.WindowManager;
import android.widget.ArrayAdapter;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import com.txl.mycamera.camera.CameraListener;
import com.txl.mycamera.camera.CameraProxy;
import com.txl.mycamera.camera.TextureHolder;
import com.txl.mycamera.utils.DirectDrawer;
import com.txl.mycamera.utils.LogUtils;
import com.txl.mycamera.utils.OpenGLUtils;
import com.txl.mycamera.utils.OrientationSensor;

import java.util.List;

import javax.microedition.khronos.egl.EGLConfig;
import javax.microedition.khronos.opengles.GL10;

public class CameraActivity extends AppCompatActivity implements GLSurfaceView.Renderer, SurfaceTexture.OnFrameAvailableListener {

    GLSurfaceView mSurfaceView;
    CameraProxy mCameraProxy;
    //cameraId（前后）
    private int mCameraID = Camera.CameraInfo.CAMERA_FACING_FRONT;
    DirectDrawer mDirectDrawer;
    float[] mtx = new float[16];
    SurfaceTexture mSurface;
    int mTextureID = -1;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        setContentView(R.layout.activity_camera);
        initViews();
    }

    private void initViews() {
        mSurfaceView = findViewById(R.id.opengl);
        mSurfaceView.setEGLContextClientVersion(2);
        mSurfaceView.setRenderer(this);
        mSurfaceView.setRenderMode(GLSurfaceView.RENDERMODE_WHEN_DIRTY);
        mCameraProxy = new CameraProxy(this);
        OrientationSensor.start(this);
    }

    @Override
    public void onSurfaceCreated(GL10 gl, EGLConfig config) {
        LogUtils.d("onSurfaceCreated: ");
        GLES20.glEnable(GL10.GL_DITHER);
        GLES20.glClearColor(0, 0, 0, 0);
        // 相机必须在opengl上下文创建好之后开启，否则在xiaomi 4LTE上会出现glError,
        openCamera();
        mDirectDrawer = new DirectDrawer();
    }

    @Override
    public void onSurfaceChanged(GL10 gl, int width, int height) {
        mDirectDrawer.setViewSize(width, height);
    }

    @Override
    public void onDrawFrame(GL10 gl) {
        //清空缓冲区颜色
        //Clear buffer color
        GLES20.glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
        GLES20.glClear(GLES20.GL_COLOR_BUFFER_BIT | GLES20.GL_DEPTH_BUFFER_BIT);
        if (!mCameraProxy.isCameraValid()) return;
        mCameraProxy.updateTexture();
        mTextureID = mCameraProxy.getPreviewTexture();
        mDirectDrawer.draw(mTextureID, mtx);
    }

    /**
     * 打开相机，根据系统版本及黑名单 自动切换camera2/camer1
     */
    public void openCamera() {
        LogUtils.d("openCamera");
        mCameraProxy.openCamera(mCameraID, new CameraListener() {
            @Override
            public void onOpenSuccess() {
                if (mSurfaceView == null) return;
                mSurfaceView.queueEvent(new Runnable() {
                    @Override
                    public void run() {
                        LogUtils.d("onOpenSuccess");
                        onCameraOpen();
                    }
                });
            }

            @Override
            public void onOpenFail() {
                LogUtils.d("onOpenFail");
            }
        });
    }


    /**
     * 相机打开成功时回调，初始化特效SDK
     * Initialize camera information (texture, etc.)
     */
    private void onCameraOpen() {
        LogUtils.d("CameraSurfaceView onCameraOpen");
        mCameraProxy.startPreview(this);
    }

    @Override
    public void onFrameAvailable(SurfaceTexture surfaceTexture) {
        if (mSurfaceView != null) {
            surfaceTexture.getTransformMatrix(mtx);
            mSurfaceView.requestRender();
        }
    }


    /**
     * 切换前后置相机
     */
    public void switchCamera() {
        switchCamera(null);
    }

    public void switchCamera(Runnable onOpenSuccess) {
        LogUtils.d("switchCamera");
        if (null == mSurfaceView) return;
        if (Camera.getNumberOfCameras() == 1) {
            return;
        }
        mCameraID = 1 - mCameraID;
        if (mSurfaceView == null) return;
        mSurfaceView.queueEvent(new Runnable() {
            @Override
            public void run() {
                mCameraProxy.changeCamera(mCameraID, new CameraListener() {
                    @Override
                    public void onOpenSuccess() {
                        if (mSurfaceView == null) return;
                        mSurfaceView.queueEvent(new Runnable() {
                            @Override
                            public void run() {
                                LogUtils.d("onOpenSuccess");
                                mCameraProxy.deleteTexture();
                                onCameraOpen();
                                if (mSurfaceView != null) {
                                    mSurfaceView.requestRender();
                                }
                                if (onOpenSuccess != null) {
                                    onOpenSuccess.run();
                                }
                            }
                        });

                    }

                    @Override
                    public void onOpenFail() {
                        LogUtils.e("camera openFail!!");


                    }
                });
            }
        });


    }
}
